<!doctype html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator="base"
      th:with="pageTitle='用户管理'">
<head>
    <link rel="stylesheet" th:href="@{/css/index.css}">

</head>

<body>

<th:block layout:fragment="custom_content">
    <h2>用户管理</h2>
    <el-button size="primary" type="small" @click="handleAdd" style="margin-bottom: 20px;">添加用户</el-button>
    <el-table :data="tableData" v-loading.body="loading" stripe style="width: 100%">
        <el-table-column prop="id" label="编号" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名" width="150"></el-table-column>
        <el-table-column prop="name" label="姓名" width="150"></el-table-column>
        <el-table-column prop="deptname" label="部门" width="150"></el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录时间" :formatter="dateFormat" width="180"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" :formatter="dateFormat" width="180"></el-table-column>
        <el-table-column prop="enable" label="是否可用" :formatter="lockFormat" width="100"></el-table-column>
        <el-table-column label="操作" width="300px">
            <template scope="scope">
                <el-button size="mini" type="info" @click="handleEdit(scope.row.id)" v-if="scope.row.id!='1'">编辑
                </el-button>
                <el-button size="mini" type="info" @click="handleEditRole(scope.row.id)" v-if="scope.row.id!='1'">配置角色</el-button>
                <el-button size="mini" type="info" @click="handleChangePassword(scope.row.id)">重置密码</el-button>
                <!--<el-button size="mini" type="danger" v-if="scope.row.enable==1 && scope.row.id!='1'" @click="handleLock(scope.row.id)">锁定-->
                <!--</el-button>-->
                <!--<el-button size="mini" type="info" v-if="scope.row.enable!=1" @click="handleNormal(scope.row.id)">正常-->
                <!--</el-button>-->
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="pageNum"
            layout="total, prev, pager, next"
            :total="total">
    </el-pagination>
    <el-dialog
            title="添加"
            :visible.sync="addDialogVisible"
            size="tiny"
            :before-close="handleAddClose" id="addDialog">
        <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="100px" id="addForm">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
                <el-input v-model="addForm.name"></el-input>
            </el-form-item>
            <el-form-item v-if="visible" label="密码" prop="password">
                <el-input type="password"  v-model="addForm.password" placeholder="请输入密码">
                </el-input>
            </el-form-item>
            <el-form-item v-if="visible" label="确认密码" prop="confirmPassword">
                <el-input type="password"  v-model="addForm.confirmPassword"
                          placeholder="请确认密码">
                </el-input>
            </el-form-item>

            <el-form-item label="所属部门" prop="deptId">
                <el-cascader
                        v-model="addForm.deptId"
                        :options="allMenus"
                        :props="props"
                        change-on-select
                ></el-cascader>
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
                <el-input v-model="addForm.phone"></el-input>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="handleAddClose">取 消</el-button>
            <el-button type="primary" @click="handleAddSave('addForm')">保存</el-button>
        </div>
    </el-dialog>
    <el-dialog
            title="配置角色"
            :visible.sync="editRoleDialogVisible"
            size="tiny"
            id="editRoleDialog">
        <el-form :model="editRoleForm"  ref="editRoleForm" label-width="100px" id="editRoleForm">
            <el-tree
                    :data="roles"
                    show-checkbox
                    default-expand-all
                    :default-checked-keys="defaultCheckedKeys"
                    node-key="id"
                    ref="tree"
                    :check-strictly="true"
                    @check-change="handleClick"
                    highlight-current
                    :props="defaultProps">
            </el-tree>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="editRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleEditRoleSave('editRoleForm')">保存</el-button>
        </div>
    </el-dialog>

    <el-dialog
            title="编辑"
            :visible.sync="editDialogVisible"
            size="tiny"
            id="editDialog">
        <el-form :model="editForm"  :rules="editRules" ref="editForm" label-width="100px" id="editForm">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="editForm.username"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
                <el-input v-model="editForm.name"></el-input>
            </el-form-item>
            <el-form-item label="所属部门" prop="deptId">
                <el-cascader
                        v-model="editForm.deptId"
                        :options="allMenus"
                        :props="props"
                        change-on-select
                ></el-cascader>
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
                <el-input v-model="editForm.phone"></el-input>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
                <el-input v-model="editForm.email"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="handleEditClose">取 消</el-button>
            <el-button type="primary" @click="handleEditSave('editForm')">保存</el-button>
        </div>
    </el-dialog>

    <el-dialog
            title="锁定提示"
            :visible.sync="lockDialogVisible"
            size="tiny">
        <span>确定锁定该用户？</span>
        <span slot="footer" class="dialog-footer">
                <el-button @click="lockDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleLockUserConfirm">确 定</el-button>
            </span>
    </el-dialog>

</th:block>
<th:block layout:fragment="javascript">
    <script th:src="@{/moment.js}"></script>
    <script>
        var listVue = new Vue({
            el: '#app',
            data: function () {
                function validateUsername  (rule, value, callback)  {
                    if (value == '') {
                        callback(new Error('请输入用户名'));
                        listVue.valUsername = false;
                    } else {
                        listVue.valUsername = true;
                    }
                };
                function validateName  (rule, value, callback)  {

                    if (value == '') {
                        callback(new Error('请输入姓名'));
                        listVue.valName = false;
                    } else {
                        listVue.valName = true;
                    }
                };
                function validatePass (rule, value, callback)  {
                    if (value == '') {
                        callback(new Error('请输入密码'));
                        listVue.valPassword = false;
                    } else if (value.length < 6 || value.length > 15) {
                        callback(new Error('密码长度应为6~15个字符'));
                        listVue.valPassword = false;
                    } else {
                        // if (listVue.addForm.password !== '') {
                        //     listVue.addForm.validateField('confirmPassword');
                        // }
                        // callback();
                        listVue.valPassword = true;
                    }
                };
                function validatePass2  (rule, value, callback)  {
                    if (value == '') {
                        callback(new Error('请输入确认密码'));
                        listVue.valConfirmPas = false;
                    } else if (value.length < 6 || value.length > 15) {
                        callback(new Error('确认密码长度应为6~15个字符'));
                        listVue.valConfirmPas = false;
                    } else if (value !== listVue.addForm.password) {
                        callback(new Error('两次输入密码不一致!'));
                        listVue.valConfirmPas = false;
                    } else {
                        callback();
                        listVue.valConfirmPas = true;
                    }
                };
                function validatePhone  (rule, value, callback)  {
                    if (value==undefined||value == '') {
                        callback(new Error('请输入手机号'));
                        listVue.validatePhone = false;
                    } else if (!isPoneAvailable(value)) {
                        callback(new Error('请输入正确的手机号!'));
                        listVue.validatePhone = false;
                    } else {
                        listVue.validatePhone = true;
                    }
                };
                function validateEmail  (rule, value, callback)  {
                    if (value==undefined||value == '') {
                        callback(new Error('请输入邮箱地址'));
                        listVue.validateEmail = false;
                    } else if (!emailCheck(value)) {
                        callback(new Error('请输入正确的邮箱地址!'));
                        listVue.validateEmail = false;
                    } else {
                        listVue.validateEmail = true;
                    }
                };
                return {
                    siderWidthDialog:false,
                    siderbarWidth:15,
                    sideActiveIndex: '2-1',
                    roles: [],
                    defaultCheckedKeys: [],
                    defaultProps: {
                        children: 'children',
                        label: 'roleName'
                    },
                    tableData: [],
                    pageNum: 0,
                    total: 0,
                    lockId: '',
                    loading: false,
                    addDialogVisible: false,
                    editRoleDialogVisible: false,
                    lockDialogVisible: false,
                    visible: true,
                    breadcrumbs:['系统管理','用户管理'],
                    allMenus:[],
                    props:{
                        value:'id',
                        label:'label',
                        children:'children',
                        disabled:'disabled'
                    },
                    addForm: {
                        username: '',
                        name: '',
                        password: '',
                        confirmPassword: '',
                        deptId: [],
                        phone:'',
                        email:'',
                    },

                    addRules: {
                        username: [
                            {validator:validateUsername, trigger: ['blur', 'change']}
                        ],
                        name: [
                            {validator:validateName, trigger: ['blur', 'change']}
                        ],
                        password: [
                            {validator: validatePass, trigger: ['blur', 'change']}
                        ],
                        confirmPassword: [
                            {validator: validatePass2, trigger: ['blur', 'change']}
                        ],
                        phone: [
                            {validator: validatePhone, trigger: ['blur', 'change']}
                        ],
                        email: [
                            {validator: validateEmail, trigger: ['blur', 'change']}
                        ]
                    },
                    editRules: {
                        username: [
                            {validator:validateUsername, trigger: ['blur', 'change']}
                        ],
                        name: [
                            {validator:validateName, trigger: ['blur', 'change']}
                        ],
                        email: [
                            {validator: validateEmail, trigger: ['blur', 'change']}
                        ]

                    },
                    editRoleForm: {
                        userId: '',
                        name: '',
                        roleIds: [],
                        phone:'',
                        email:'',
                    },
                    editForm: {
                        username: '',
                        name: '',
                        deptId: [],
                    },
                    editDialogVisible: false,
                    valUsername: false,
                    valName:false,
                    valPassword: false,
                    valConfirmPas:false,
                    validatePhone:false,
                    validateEmail:false,
                    isCollapse: false,
                    defaultIndex: '1',
                    menus: [],
                    regulationMenus: [],
                    deptTrees:[]
                }
            },
            methods: {
                handleEdit: function (id) {
                    var $this = this;
                    $.ajax({
                        cache: true,
                        url: '/user/edit?newDate='+Math.random(),
                        type: 'GET',
                        data: {userId: id},
                        dataType: 'json',
                        contentType: 'application/json',
                        async: false,
                        success: function (data) {
                            if (data.status == 1) {
                                listVue.editForm = data.value;
                                listVue.editForm.deptId = listVue.editForm.fullUrlArr;
                                listVue.selectedOptions = listVue.editForm.fullUrlArr;
                                listVue.selectedOptionsBf = listVue.editForm.fullUrlArr;
                                listVue.editDialogVisible = true;
                                $this.$nextTick(function(){
                                    changeFooterHeight();
                                })
                            }
                        }
                    });
                },
                clearValidate: function (formName) {
                    this.$refs[formName].clearValidate();
                },
                handleCurrentChange: function (val) {
                    search('${val}');
                },
                handleAddClose: function () {
                    listVue.addForm = {username: '', name: '',password: '', confirmPassword: ''};
                    this.clearValidate('addForm'); // 清除整个表单的校验
                    listVue.addDialogVisible = false;
                },
                handleEditClose: function () {
                    this.$refs["editForm"].resetFields();

                    listVue.editForm = {name: '', parentId:[]};
                    listVue.editDialogVisible = false;
                },
                handleAddSave: function (formName) {
                    var $this = this;
                    if (listVue.addForm.deptId == undefined || listVue.addForm.deptId == 0) {
                        $this.$alert('请选择部门！', '提示', {
                            confirmButtonText: '确定',
                            callback: function callback() {

                            }
                        });
                        return;
                    }
                    if(!listVue.valUsername || !listVue.valName ||!listVue.valPassword ||!listVue.valConfirmPas||!listVue.validatePhone||!listVue.validateEmail){
                        $this.$message('请填写正确的数据!');
                        return;
                    }

                    if (listVue.addForm.deptId != '') {
                        var deptId = listVue.addForm.deptId;
                        listVue.addForm.fullUrl = deptId.toString();
                        listVue.addForm.deptId = listVue.addForm.deptId[deptId.length-1];

                    }

                    $.ajax({
                        cache: false,
                        url: '/user/add',
                        type: 'POST',
                        data: JSON.stringify(listVue.addForm),
                        dataType: 'json',
                        contentType: 'application/json',
                        async: false,
                        success: function (data) {
                            if (data.status == 1) {
                                $this.$message('保存成功');
                                listVue.addDialogVisible = false;
                                listVue.addForm = {username: '',name:'', password: '', confirmPassword: ''};
                                search(listVue.pageNum);
                            } else {
                                $this.$message.error(data.msg);
                            }
                        }
                    });

                    changeFooterHeight();
                },
                handleEditSave: function (formName) {
                    var $this = this;
                    if (listVue.editForm.deptId == undefined || listVue.editForm.deptId == 0) {
                        $this.$alert('请选择部门！', '提示', {
                            confirmButtonText: '确定',
                            callback: function callback() {

                            }
                        });
                        return;
                    }
                    if (listVue.editForm.username == undefined || listVue.editForm.username == '') {
                        $this.$alert('请填写用户名！', '提示', {
                            confirmButtonText: '确定',
                            callback: function callback() {

                            }
                        });
                        return;
                    }

                    if (listVue.editForm.name == undefined || listVue.editForm.name == '') {
                        $this.$alert('请填写姓名！', '提示', {
                            confirmButtonText: '确定',
                            callback: function callback() {

                            }
                        });
                        return;
                    }
                    if (listVue.editForm.phone==undefined||listVue.editForm.phone == '') {
                        $this.$alert('请填写手机号！', '提示', {
                            confirmButtonText: '确定',
                            callback: function callback() {

                            }
                        });
                        return;
                    }

                    if (!isPoneAvailable(listVue.editForm.phone)) {
                        $this.$alert('请填写正确的手机号！', '提示', {
                            confirmButtonText: '确定',
                            callback: function callback() {

                            }
                        });
                        return;
                    }
                    if (listVue.editForm.email==undefined||listVue.editForm.email == '') {
                        $this.$alert('请填写邮箱地址！', '提示', {
                            confirmButtonText: '确定',
                            callback: function callback() {

                            }
                        });
                        return;
                    }

                    if (!emailCheck(listVue.editForm.email)) {
                        $this.$alert('请填写正确的邮箱地址！', '提示', {
                            confirmButtonText: '确定',
                            callback: function callback() {

                            }
                        });
                        return;
                    }

                    if (listVue.editForm.deptId != '') {
                        var deptId = listVue.editForm.deptId;
                        listVue.editForm.fullUrl = "0,"+deptId.toString();
                        listVue.editForm.deptId = listVue.editForm.deptId[deptId.length-1];

                    }



                    $.ajax({
                        cache: false,
                        url: '/user/update',
                        type: 'POST',
                        data: JSON.stringify(listVue.editForm),
                        dataType: 'json',
                        contentType: 'application/json',
                        async: false,
                        success: function (data) {
                            if (data.status == 1) {
                                $this.$message('保存成功');
                                listVue.editDialogVisible = false;
                                search(listVue.pageNum);
                            } else {
                                $this.$message.error(data.msg);
                            }
                        }
                    });

                    changeFooterHeight();
                },
                handleEditRoleSave: function (formName) {
                    this.editRoleForm.roleIds = this.getCheckedKeys();
                    var $this = this;
                    $.ajax({
                        cache: false,
                        url: '/user/role/edit',
                        type: 'POST',
                        data: JSON.stringify(listVue.editRoleForm),
                        dataType: 'json',
                        contentType: 'application/json',
                        async: false,
                        success: function (data) {
                            if (data.status == 1) {
                                $this.$message('更新成功');
                                listVue.editRoleDialogVisible = false;
                                listVue.editRoleForm = {userId: '', roleIds: []};
                                search(listVue.pageNum);
                            } else {
                                $this.$message.error(data.msg);
                            }
                        }
                    });
                },
                handleChangePassword:function(id){
                    var $this = this;
                    // listVue.$confirm('确定重置密码？', '提示', {
                    //     confirmButtonText: '确定',
                    //     cancelButtonText: '取消',
                    //     type: 'warning'}).then(function(){
                    $.ajax({
                        cache: false,
                        url: '/user/changePwd',
                        type: 'GET',
                        data: {userId:id},
                        dataType: 'json',
                        contentType: 'application/json',
                        async: false,
                        success: function (data) {
                            if (data.status == 1) {
                                $this.$message('密码已重置');
                            } else {
                                $this.$message.error(data.msg);
                            }
                        }
                    });
                    // });
                },
                handleLockUserConfirm: function () {
                    listVue.lockDialogVisible = false;
                    var $this = this;
                    $.ajax({
                        cache: false,
                        url: '/user/lock',
                        type: 'GET',
                        data: {userId: listVue.lockId},
                        dataType: 'json',
                        contentType: 'application/json',
                        async: false,
                        success: function (data) {
                            if (data.status == 1) {
                                $this.$message({
                                    showClose: true,
                                    message: '该用户已锁定',
                                    type: 'success'
                                });
                                search(listVue.pageNum);
                            }
                        }
                    });
                },
                handleClick: function (data, checked, node) {
                    if (checked == true) {
                        this.checkedId = data.id;
                        this.$refs.tree.setCheckedNodes([data]);
                    }
                },
                handleNormal: function (id) {
                    var $this = this;
                    $.ajax({
                        cache: false,
                        url: '/user/recoveryUser',
                        type: 'GET',
                        data: {userId: id},
                        dataType: 'json',
                        contentType: 'application/json',
                        async: false,
                        success: function (data) {
                            if (data.status == 1) {
                                $this.$message({
                                    showClose: true,
                                    message: '该用户已恢复正常',
                                    type: 'success'
                                });
                                search(listVue.pageNum);
                            }
                        }
                    });
                },
                handleEditRole: function (id) {
                    var $this = this;
                    $.ajax({
                        cache: false,
                        url: '/user/role/edit',
                        type: 'GET',
                        data: {userId: id},
                        dataType: 'json',
                        contentType: 'application/json',
                        async: false,
                        success: function (data) {
                            if (data.status == 1) {
                                listVue.editRoleForm = data.value;
                                listVue.editRoleForm.userId = id;
                                listVue.roles = data.value.roles;
                                listVue.defaultCheckedKeys = data.value.roleIds;
                                listVue.editRoleDialogVisible = true;
                            }
                        }
                    });
                },
                handleAdd: function () {
                    listVue.addForm = {username: '', name:'',password: '', confirmPassword: ''};
                    listVue.addDialogVisible = true;
                },
                handleLock: function (id) {
                    listVue.lockDialogVisible = true;
                    listVue.lockId = id;
                },
                getCheckedKeys: function () {
                    return this.$refs.tree.getCheckedKeys();
                },
                setCheckedKeys: function (ids) {
                    this.$refs.tree.setCheckedKeys(ids);
                },
                resetChecked: function () {
                    this.$refs.tree.setCheckedKeys([]);
                },
                changePass: function (value) {
                    this.visible = !(value === 'show');
                },
                addHeight: function () {
                    var $this = this;
                    $this.$nextTick(function () {
                        changeFooterHeight();
                    })
                },
                //时间格式化
                dateFormat: function (row, column) {
                    var date = row[column.property];
                    if (date == undefined) {
                        return "";
                    }
                    return moment(date).format("YYYY-MM-DD HH:mm:ss");
                },
                lockFormat: function (row, column) {
                    if (row[column.property] == 1) {
                        return '正常';
                    } else {
                        return '锁定';
                    }
                },
                initMenu: function () {
                    var $this = this;
                    var data = commonInitMenu($this);
                },
                toggleMenu: function () {
                    this.isCollapse = !this.isCollapse;
                    window.localStorage.setItem('isCollapse',this.isCollapse);
                },
                changeSiderWidth:function(value){
                    changeSiderWidth(this,value);
                },
                openChangeSiderWidth:function(){
                    this.siderWidthDialog=true;
                }
            },
            created: function () {
                initCssProperty(this);
            }

        });

        function isPoneAvailable(phone) {
            var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
            if (!myreg.test(phone)) {
                return false;
            } else {
                return true;
            }
        }
        function emailCheck(mail) {
            var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if (filter.test(mail)) {
                return true;
            } else {
                return false;
            }
        }

        function search(pageNum) {
            listVue.loading = true;
            var condition = {};
            condition['pageNum'] = listVue.pageNum;
            $.ajax({
                cache: false,
                url: '/user/list?newDate='+Math.random(),
                type: 'POST',
                data: JSON.stringify(condition),
                dataType: 'json',
                contentType: 'application/json',
                async: false,
                success: function (data) {
                    listVue.loading = false;
                    if (data.status == 1) {
                        var pageInfo = data.value;
                        listVue.tableData = pageInfo.list;
                        listVue.pageNum = pageInfo.pageNum;
                        listVue.total = pageInfo.total;
                        listVue.addHeight();
                    }
                }
            });
        }

        $(function () {
            listVue.initMenu();

            var data = {};
            $.ajax({
                cache: true,
                url: '/dept/all?newDate=' + Math.random(),
                type: 'GET',
                data: data,
                dataType: 'json',
                contentType: 'application/json',
                async: true,
                success: function (data) {

                    if (data.status == 1) {
                        if (data.value.menus) {
                            listVue.deptmenus = data.value.menus;
                        }

                        var allMenu = [{
                            id: 0,
                            name: '部门列表',
                            label: '部门列表',
                            disabled: false,
                            children:  listVue.deptmenus,
                        }];
                        listVue.allMenus = allMenu;

                        if ($('.siderbar [tabindex="-1"].is-active').offset()) {
                            $('.siderbar').animate({
                                scrollTop: $('.siderbar [tabindex="-1"].is-active').offset().top
                            }, 1);

                        }
                    }
                    // return data;
                }
            });

            search(1);
            // changeFooterHeight();
        })
    </script>
</th:block>
</body>
</html>